;(function(undefined) {
    "use strict"
    var _global;

    function result(args,fn){
        var argsArr = Array.prototype.slice.call(args);
        if(argsArr.length > 0){
            return argsArr.reduce(fn);
        } else {
            return 0;
        }
    }
    var  rightsList = {
    	selectRoleCode: '',
    	selectUserCode: '',
        roleColumnsInit:function(){
            return  [
	            {
	            	radio: true
	            },
	            {
	                field: 'od',
	                title: '序号',
	                width:'5%',
	                align:'center',
	                formatter: function (value, row, index) {
	                    return index + 1;
	                }
	            },
	            {
	                field: 'roleName',
	                title: '角色名称'
	            },
	            {
	                field: 'roleCode',
	                title: '角色编码'
	            },
	            {
	                field: 'option',
	                title: '操作',
	                width: 80,
	                align: 'center',
	                formatter: function (value, row, index) {
	                    return '<a class="opt-icon" href="javascript:;" onclick="settingRoleUser(\''+row.roleName+'\',\''+row.roleCode+'\');"><i class="glyphicon glyphicon-duplicate"></i></a>';
	                }
	            }
            ]
        },
        userColumnsInit:function(){
            return  [
	            {
	            	radio: true
	            },
	            {
	                field: 'od',
	                title: '序号',
	                width:'5%',
	                align:'center',
	                formatter: function (value, row, index) {
	                    return index + 1;
	                }
	            },
	            {
	                field: 'userName',
	                title: '用户姓名'
	            },
	            {
	                field: 'userCode',
	                title: '登录账号'
	            },
	            {
	                field: 'option',
	                title: '操作',
	                width: 80,
	                align: 'center',
	                formatter: function (value, row, index) {
	                    return '<a class="opt-icon" href="javascript:;" onclick="settingUserRole(\''+row.userName+'\',\''+row.userCode+'\');"><i class="glyphicon glyphicon-duplicate"></i></a>';
	                }
	            }
            ]
        },
        roleGridInit:function(columns){
            return $("#roleTable").bootstrapTable({
            	method: "post",
                contentType: "application/x-www-form-urlencoded",
                url:$$.restServerUrl + '/bootstrap/basegrid/BaseRoleBusiness/list',
                columns: columns,
                undefinedText: '-',
                striped: 'true',
                classes: 'table table-hover qxttable',
                height: ($('#rightCont').height())/2-56,
                pagination: 'true',
                clickToSelect: true,
                singleSelect: false,
                sidePagination: "server",
                queryParamsType: "page",
                sortSide: 'client',
                sortable: true,
                pageNumber: 1,
                pageSize: 10,
                idField: 'id',
                silentSort: true,
                pageList: [
                    10, 20, 50, 100
                ],
                queryParams: function queryParams(params) {//设置查询参数
                    var args = {};
                    var roleName = $("#roleName").val();
                    var roleCode = $("#roleCode").val();
                    if(roleName!==""){
                    	args.c_roleName_7 = roleName;
                    }
                    if(roleCode!==""){
                    	args.c_roleCode_7 = roleCode;
                    }
                    args.page = params.pageNumber - 1;//params.pageNumber
                    args.pageSize = params.pageSize;//params.pageSize
                    args.isPage = 1;
                    var paramStr = JSON.stringify(args);
                    var param = {
                        params: paramStr
                    };
                    return param;
                },
	            onCheck:function(row){
	            	var roleCode = row.roleCode;
	            	rightsList.selectRoleCode = roleCode;
	            	rightsList.selectUserCode = "";
	            	saveDataButtonSet();
	            	$("#select-tip-info").html("角色权限："+row.roleName+"("+roleCode+")");
	            	showRoleMenu(roleCode);
	            },
	            onLoadSuccess:function(data){
	            	rightsList.selectRoleCode = "";
	            	saveDataButtonSet();
	            }
            });
        },
        userGridInit:function(columns){
            return $("#userTable").bootstrapTable({
            	method: "post",
                contentType: "application/x-www-form-urlencoded",
                url:$$.restServerUrl + '/bootstrap/basegrid/BaseUserBusiness/list',
                columns: columns,
                undefinedText: '-',
                striped: 'true',
                classes: 'table table-hover qxttable',
                height: ($('#rightCont').height())/2-56,
                pagination: 'true',
                clickToSelect: true,
                singleSelect: false,
                sidePagination: "server",
                queryParamsType: "page",
                sortSide: 'client',
                sortable: true,
                pageNumber: 1,
                pageSize: 10,
                idField: 'id',
                silentSort: true,
                pageList: [
                    10, 20, 50, 100
                ],
                queryParams: function queryParams(params) {//设置查询参数
                    var args = {};
                    var userName = $("#userName").val();
                    var userCode = $("#userCode").val();
                    if(userName!==""){
                    	args.c_userName_7 = userName;
                    }
                    if(userCode!==""){
                    	args.c_userCode_7 = userCode;
                    }
                    args.c_status_1 = 1;
                    args.page = params.pageNumber - 1;//params.pageNumber
                    args.pageSize = params.pageSize;//params.pageSize
                    args.isPage = 1;
                    var paramStr = JSON.stringify(args);
                    var param = {
                        params: paramStr
                    };
                    return param;
                },
	            onCheck:function(row){
	            	var userCode = row.userCode;
	            	rightsList.selectRoleCode = "";
	            	rightsList.selectUserCode = userCode;
	            	saveDataButtonSet();
	            	$("#select-tip-info").html("用户权限："+row.userName+"("+userCode+")");
	            	showUserMenu(userCode);
	            },
	            onLoadSuccess:function(data){
	            	rightsList.selectUserCode = "";
	            	saveDataButtonSet();
	            }
            });
        }
    };

    // 将插件对象暴露给全局对象
    _global = (function(){ return this || (0, eval)('this'); }());
    if (typeof module !== "undefined" && module.exports) {
        module.exports = rightsList;
    } else if (typeof define === "function" && define.amd) {
        define(function(){return rightsList;});
    } else {
        !('plugin' in _global) && (_global.rightsList = rightsList);
    }
}());

/**
 * 权限树
 */
function initMenuTree(){
	//开启遮罩，防止左侧数据加载完并且点击返回数据，右侧权限树未加载完成的情况发生
	var indexLoad = layer.load(2);
	//数据源
	var source = {
	    type: 'post',
	    root: 'data',
	    dataType: "json",
	    dataFields: [{
	        name: "id",
	        type: "string"
		},{
	        name: "pid",
	        type: "string"
		},{
	        name: "menuCode",
	        type: "string"
		},{
	        name: "menuName",
	        type: "string"
		},{
	        name: "menuPath",
	        type: "string"
		},{
			name: "level",
	        type: "string"
		},{
			name: "isLeaf",
	        type: "string"
		},{
            name: "status",
            type: "string"
        },{
            name: "rowSort",
            type: "number"
        },{
            name: "remarks",
            type: "string"
        }],
		hierarchy: {
		    keyDataField: { name: 'id' },
	        parentDataField: { name: 'pid' }
		},
		id: "id"
	};
	
	//数据适配器
	var dataAdapter = new $.jqx.dataAdapter(source, {
		beforeSend: function(jqXHR, settings){
			var storage = window.localStorage;
			if(storage){
				var token = storage.getItem("hgtg-token");
				if(token){
					jqXHR.setRequestHeader("token",token);
				}
			}
		},
	    loadComplete: function () {
	    	$("#rightsTable").jqxTreeGrid('uncheckRow', 0);
	    	//指定排序列
	    	$("#rightsTable").jqxTreeGrid('sortBy', 'rowSort', 'asc');
	    	//展开树
	    	$("#rightsTable").jqxTreeGrid('expandAll');
	    },
	    downloadComplete: function(edata, textStatus, jqXHR){
	    	layer.close(indexLoad);//关闭遮罩
	    	if(edata && edata.code && edata.code==403){
	    		$$.goUrl("/login/login.html");
	    	}
	    }
	});
	
	//表格
    $("#rightsTable").jqxTreeGrid({
        source: dataAdapter,
        width: '100%',
        altRows: true,
        height: $('#rightCont').height()-70,
        selectionMode: "singleRow",
        showToolbar: false,
        theme: 'bootstrap',
        checkboxes: true,
        hierarchicalCheckboxes: true,
        columns: [
	        {
	            text: "权限",
	            align: "center",
	            dataField: "menuName"
	        }
        ],
        ready:function(){
        	$('#rightsTable').jqxTreeGrid({disabled:true});
        }
    });
     
    //加载菜单数据
    source.url = $$.restServerUrl + '/rest/BaseMenuBusiness/listAll';
	$('#rightsTable').jqxTreeGrid('updateBoundData');
	
}

/**
 * 角色分配用户
 * @param {Object} roleName
 * @param {Object} roleCode
 */
function settingRoleUser(roleName,roleCode) {
   	var openWin;
   	var title = "角色分配用户-"+roleName+"("+roleCode+")";
    layer.open({
        move: false,
        type: 2,
        title: title,
        area: ['900px', '500px'],
        content: 'rights_addUser.html',
        btn: ['关闭'],
        btnAlign: 'c',
        success: function (layero, index) {
            openWin = window[layero.find('iframe')[0]['name']];
            openWin.initData(roleCode);
        },
        yes: function (index, layero) {
        	layer.close(index);
        }, cancel: function (index) {
            layer.close(index);
        }
    });
}

/**
 * 用户分配角色
 * @param {Object} userName
 * @param {Object} userCode
 */
function settingUserRole(userName,userCode) {
   	var openWin;
   	var title = "用户分配角色-"+userName+"("+userCode+")";
    layer.open({
        move: false,
        type: 2,
        title: title,
        area: ['900px', '500px'],
        content: 'rights_addRole.html',
        btn: ['关闭'],
        btnAlign: 'c',
        success: function (layero, index) {
            openWin = window[layero.find('iframe')[0]['name']];
            openWin.initData(userCode);
        },
        yes: function (index, layero) {
        	layer.close(index);
        	showUserMenu(rightsList.selectUserCode);
        }, cancel: function (index) {
            layer.close(index);
            showUserMenu(rightsList.selectUserCode);
        }
    });
}

/**
 * 显示角色权限
 * @param {Object} roleCode
 */
function showRoleMenu(roleCode){
	if(roleCode!==""){
		var indexLoad = layer.load(2);
		var args = {};
		args.roleCode = roleCode;
		//重置菜单树
		$("#rightsTable").jqxTreeGrid('uncheckRow', 0);
		//获取角色拥有的权限id
		$$.ajax({
	        url:"/rest/BaseMenuRightsBusiness/listByRoleCode",
	        data: args,
	        success: function(data){
	        	setMenuTreeSelect(data);
	        	layer.close(indexLoad);
	        },
	        error: function(){
	        	layer.close(indexLoad);
	        }
    	});
	}
}

/**
 * 显示用户权限
 * @param {Object} userCode
 */
function showUserMenu(userCode){
	if(userCode!==""){
		var indexLoad = layer.load(2);
		var args = {};
		args.userCode = userCode;
		//重置菜单树
		$("#rightsTable").jqxTreeGrid('uncheckRow', 0);
		//获取用户拥有的角色对应的权限id
		$$.ajax({
	        url:"/rest/BaseMenuRightsBusiness/listByUserCode",
	        data: args,
	        success: function(data){
	        	setMenuTreeSelect(data);
	        	layer.close(indexLoad);
	        },
	        error: function(){
	        	layer.close(indexLoad);
	        }
	    });
	}
}

/**
 * 设置权限选中
 * @param {Object} menuIds
 */
function setMenuTreeSelect(menuList){
	//设置选中
	if(menuList && menuList.length>0){
		for(var i=0;i<menuList.length;i++){
			$("#rightsTable").jqxTreeGrid('checkRow', menuList[i].menuId);
		}
	}
	//展开树
	$("#rightsTable").jqxTreeGrid('expandAll');
}

/**
 *	设置保存按钮的显示和隐藏
 */
function saveDataButtonSet(){
	if(rightsList.selectRoleCode!==""){
		$('#saveData').show();
		$('#rightsTable').jqxTreeGrid({disabled:false});
	}else{
		$('#rightsTable').jqxTreeGrid({disabled:true});
		$('#saveData').hide();
		if(rightsList.selectUserCode===""){//没有选中的，重置权限树
			$("#rightsTable").jqxTreeGrid('uncheckRow', 0);
			$("#select-tip-info").html("");
		}
	}
}

$(function () {
    
    $('#saveData').hide();
    
    $('#roleName').focus();
    
    //初始化菜单树
    initMenuTree();
    
    //渲染表格-角色
    var roleColumns = rightsList.roleColumnsInit();
    var roleTable = rightsList.roleGridInit(roleColumns);
    
    //渲染表格-用户
    var userColumns = rightsList.userColumnsInit();
    var userTable = rightsList.userGridInit(userColumns);
    
    //重置-角色
	$('#searchResetRole').on('click',function(){
		rightsList.selectRoleCode = "";
    	saveDataButtonSet();
		$('.entrer-query-role').val('');
		$('#roleTable').bootstrapTable('refresh');
	});
	
    //搜索-角色
	$('#serachBtnRole').on('click',function(){
		rightsList.selectRoleCode = "";
    	saveDataButtonSet();
		$('#roleTable').bootstrapTable('refresh');
	});
	
	//回车搜索-角色
    $('.entrer-query-role').bind('keypress',function(e){
        if(e.keyCode == 13){
        	rightsList.selectRoleCode = "";
    		saveDataButtonSet();
            $('#roleTable').bootstrapTable('refresh');
        }
    });
	
	//重置-用户
	$('#searchResetUser').on('click',function(){
		rightsList.selectUserCode = "";
		saveDataButtonSet();
		$('.entrer-query-user').val('');
		$('#userTable').bootstrapTable('refresh');
	});
	
	//搜索-用户
	$('#serachBtnUser').on('click',function(){
		rightsList.selectUserCode = "";
		saveDataButtonSet();
		$('#userTable').bootstrapTable('refresh');
	});
	
	//回车搜索-用户
    $('.entrer-query-user').bind('keypress',function(e){
        if(e.keyCode == 13){
        	rightsList.selectUserCode = "";
        	saveDataButtonSet();
            $('#userTable').bootstrapTable('refresh');
        }
    });
    
    //保存权限数据
	$('#saveData').on('click',function(){
		var selectRoleCode = rightsList.selectRoleCode;
		if(selectRoleCode!==""){
			var indexLoad = layer.load(2);
			var indexTips = layer.tips('正在努力保存数据，请等待...','#saveData',{time:30*60*1000});
			var selectLeafIds = new Array();
			var checkedRows = $("#rightsTable").jqxTreeGrid('getCheckedRows');
	      	for (var i = 0; i < checkedRows.length; i++) {
	          	var rowData = checkedRows[i];
	          	if(rowData.isLeaf==1){
	          		selectLeafIds.push(rowData.id);
	          	}
	      	}
	      	var args = {};
			args.roleCode = selectRoleCode;
			args.menuIds = selectLeafIds.join(',');
	      	$$.ajax({
		        url:"/rest/BaseMenuRightsBusiness/saveRoleMenuData",
		        data : args,
		        success : function(res){
		        	layer.close(indexLoad);
		        	layer.close(indexTips);
		        	layer.tips("保存成功！",'#saveData',{time:1000});
		        },
		        error: function(){
		        	layer.close(indexLoad);
		        	layer.close(indexTips);
		        	layer.tips("保存失败，请稍后重试！",'#saveData',{time:1000});
		        }
		    });
		}else{
			layer.tips("请选择角色！",'#saveData',{time:1000});
		}
	});
    
	//动态计算表格高度
    $(window).resize(function () {
        $('#roleTable , #userTable').bootstrapTable('resetView', {
            height: ($('#rightCont').height())/2-56
        });
        $("#rightsTable").jqxTreeGrid({
            height: $('#rightCont').height()-70
        });
    });
    
})
